package org.one.afternoon.provider.xunfei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class ChatListener extends WebSocketListener {
    // 地址与鉴权信息  https://spark-api.xf-yun.com/v1.1/chat   1.5地址  domain参数为general
    // 地址与鉴权信息  https://spark-api.xf-yun.com/v2.1/chat   2.0地址  domain参数为generalv2
    public static final String hostUrl = "https://spark-api.xf-yun.com/v3.1/chat";
    public static final String appid = "e8b16518";
    public static final String apiSecret = "NTQzZWJlMGE3NTU0M2EyODQ5MDU1YmRk";
    public static final String apiKey = "41c21254d6ede7ae183fa56b66b752ba";

    public volatile static boolean end = false;

    public static List<RoleContent> historyList = new ArrayList<>(); // 对话历史存储集合

    public static String totalAnswer = ""; // 大模型的答案汇总

    // 环境治理的重要性  环保  人口老龄化  我爱我的祖国
    public static String NewQuestion = "";

    public static final Gson gson = new Gson();

    // 个性化参数
    private String userId;
    public static Boolean wsCloseFlag = false;

    private static Boolean totalFlag = true; // 控制提示用户是否输入

    // 构造函数
    public ChatListener(String userId, Boolean wsCloseFlag) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
    }

    // 主函数,用于开启WebSocket
    public static void connect(String question) throws Exception {
        // 个性化参数入口，如果是并发使用，可以在这里模拟
        log.info("①:接口调用... end:" + end + " wsCloseFlag:" + wsCloseFlag);
        //用户是否输入
        if (totalFlag) {

            //用户输入完后将totalFlag置为false
            totalFlag = false;

            //拿到服务端的参数
            NewQuestion = question;

            // 构建鉴权url:https://spark-api.xf-yun.com/v3.5/chat?authorization=YXBpX2tleT0iNDFjMjEyNTRkNmVkZTdhZTE4M2ZhNTZiNjZiNzUyYmEiLCBhbGdvcml0aG09ImhtYWMtc2hhMjU2IiwgaGVhZGVycz0iaG9zdCBkYXRlIHJlcXVlc3QtbGluZSIsIHNpZ25hdHVyZT0ib0p4c1A1T24rNlhvYVVSeGt2ZDhjeC9wakJzZm8vQTEreXA0VXFjMGZ2Zz0i&date=Wed%2C%2017%20Apr%202024%2001%3A07%3A00%20GMT&host=spark-api.xf-yun.com
            String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);

            // 获取一个新的OkHttpClient构造对象
            OkHttpClient client = new OkHttpClient.Builder().build();

            // 将authUrl中的 "http" 替换为 "ws", "https" 替换为 "wss"
            String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");

            // 构造一个request对象
            // Request{method=GET, url=https://spark-api.xf-yun.com/v3.5/chat?authorization=YXBpX2tleT0iNDFjMjEyNTRkNmVkZTdhZTE4M2ZhNTZiNjZiNzUyYmEiLCBhbGdvcml0aG09ImhtYWMtc2hhMjU2IiwgaGVhZGVycz0iaG9zdCBkYXRlIHJlcXVlc3QtbGluZSIsIHNpZ25hdHVyZT0iWlV5cXFxcWd0MWVQc0NQQzZVQ3RHSG9oWGUrZDJjZzlTZldGSTMrdmFnaz0i&date=Wed%2C%2017%20Apr%202024%2001%3A37%3A15%20GMT&host=spark-api.xf-yun.com}
            Request request = new Request.Builder().url(url).build();

            for (int i = 0; i < 1; i++) {
                totalAnswer = "";
                log.info("②:webSocket连接中...");
                WebSocket webSocket = client.newWebSocket(request, new ChatListener(i + "",
                        false));
                if (end) {
                    end = false;
                }
            }
        } else {
            Thread.sleep(200);
        }
//        }
    }

    /***
     * 鉴权方法
     * @param hostUrl 接口地址
     * @param apiKey key
     * @param apiSecret secret
     * @return 鉴权地址
     */
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {

        // 构建URL对象
        // hostUrl:https://spark-api.xf-yun.com/v3.5/chat
        URL url = new URL(hostUrl);

        // 构建时间格式化模板
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

        // 设置时区为格林尼治
        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        // 获取当前时间并格式化
        // eg. Wed, 17 Apr 2024 01:08:51 GMT
        String date = format.format(new Date());

        // 进行预处理拼接
        // host: spark-api.xf-yun.com
        // date: Wed, 17 Apr 2024 01:08:51 GMT
        // GET /v3.5/chat HTTP/1.1
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);

        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));


        // Base64加密:lRLWmA6eetZplJe5Om3wIZ5XiCNkCFhV1s6VddSM02A=
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);

        // 拼接鉴权
        // api_key="41c21254d6ede7ae183fa56b66b752ba", algorithm="hmac-sha256", headers="host date request-line", signature="XY1j1yf5QUPvjKQgx0KnFudu+lE03nBcA1ovYWpnUgQ="
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);

        // 拼接地址
        // https://spark-api.xf-yun.com/v3.5/chat?authorization=YXBpX2tleT0iNDFjMjEyNTRkNmVkZTdhZTE4M2ZhNTZiNjZiNzUyYmEiLCBhbGdvcml0aG09ImhtYWMtc2hhMjU2IiwgaGVhZGVycz0iaG9zdCBkYXRlIHJlcXVlc3QtbGluZSIsIHNpZ25hdHVyZT0ibFJMV21BNmVldFpwbEplNU9tM3dJWjVYaUNOa0NGaFYxczZWZGRTTTAyQT0i&date=Wed%2C%2017%20Apr%202024%2001%3A26%3A44%20GMT&host=spark-api.xf-yun.com
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());

        // 返回带参地址: domain + authorization + date + host
        return httpUrl.toString();
    }

    /***
     * 当WebSocket连接成功时自动执行onOpen函数
     * @param webSocket
     * @param response
     */
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        log.info("③:WebSocket连接成功 end:" + end + " wsCloseFlag:" + wsCloseFlag);
        System.out.println("*************************************************************************************");
        System.out.print("大模型：");
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }

    public static boolean canAddHistory() {  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length = 0;
        for (RoleContent temp : historyList) {
            history_length = history_length + temp.content.length();
        }
        if (history_length > 12000) {
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        } else {
            return true;
        }
    }

    /***
     * 自定义一个新线程
     */
    class MyThread extends Thread {

        // 用于操作的webSocket对象
        private WebSocket webSocket;

        // 线程的构造方法
        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        /***
         * 重写run方法,该线程用来发送音频与参数
         */
        public void run() {
            try {

                // 创建请求的数据对象: payload + parameter + header
                JSONObject requestJson = new JSONObject();

                // 创建请求的header参数: uid + app_id
                JSONObject header = new JSONObject();

                // 构造header参数:{"uid":"d8a7ed9a-5","app_id":"e8b16518"}
                header.put("app_id", appid);
                header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                // 构造parameter参数:{"chat":{"max_tokens":4096,"domain":"generalv3.5","temperature":0.5}}
                JSONObject parameter = new JSONObject();
                JSONObject chat = new JSONObject();
                chat.put("domain", "generalv3");
                chat.put("temperature", 0.5);
                chat.put("max_tokens", 4096);
                parameter.put("chat", chat);

                // 构造payload参数: message
                JSONObject payload = new JSONObject();

                // 构造message参数: text
                JSONObject message = new JSONObject();

                // 构造text参数: role + content
                JSONArray text = new JSONArray();

                // 历史问题获取
                if (historyList.size() > 0) {
                    for (RoleContent tempRoleContent : historyList) {
                        text.add(JSON.toJSON(tempRoleContent));
                    }
                }

                // 最新问题
                RoleContent roleContent = new RoleContent();
                roleContent.role = "user";
                roleContent.content = NewQuestion;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);
                message.put("text", text);
                payload.put("message", message);

                // 拼接请求参数,且为Json格式
                // {"payload":{"message":{"text":[{"role":"user","content":"唱跳rap篮球"}]}},"parameter":{"chat":{"max_tokens":4096,"domain":"generalv3.5","temperature":0.5}},"header":{"uid":"d8a7ed9a-5","app_id":"e8b16518"}}
                requestJson.put("header", header);
                requestJson.put("parameter", parameter);
                requestJson.put("payload", payload);

                // System.err.println(requestJson); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());
                log.info("④:已向服务器传输完所有数据... end:" + end + " wsCloseFlag:" + wsCloseFlag);
                // 等待服务端返回完毕后关闭
                while (true) {
                    // System.err.println(wsCloseFlag + "---");
                    Thread.sleep(200);
                    if (wsCloseFlag) {
                        log.info("①:服务器正常关闭... end:" + end + " wsCloseFlag:" + wsCloseFlag);
                        break;
                    }
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 当WebSocket保持连接并且收到服务器的消息后自动执行
     * @param webSocket webSocket对象
     * @param text 服务器返回的文本结果
     */
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        log.info("1--->" + text);

        // System.out.println(userId + "用来区分那个用户的结果" + text);

        // 获取服务端传来的数据
        // JsonParse{header=Header{code=0, status=0, sid='cht000b25ab@dx18eea102f30b894550'}, payload=Payload{choices=Choices{text=[Text{role='assistant', content='1'}]}}}
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);

        // code为0则WebSocket连接有问题,打印错误信息并关闭WebSocket
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }

        // 获取消息列表,由role和content组成
        // [Text{role='assistant', content='1'}]
        List<Text> textList = myJsonParse.payload.choices.text;

        // 因为服务器传来的数据是片段化的,因此需要拼接答案,并赋值给totalAnswer
        for (Text temp : textList) {
            log.info(temp.content);
            totalAnswer = totalAnswer + temp.content;
        }

        // status是当前获取数据的状态,0为开始获取,1为正在获取,2为获取完毕
        if (myJsonParse.header.status == 2) {
            log.info("①:已获取完服务器返回的所有数据... end:" + end + " wsCloseFlag:" + wsCloseFlag);
            // 可以关闭连接，释放资源
            System.out.println(totalAnswer);
            System.out.println("*************************************************************************************");
            if (canAddHistory()) {
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            } else {
                historyList.remove(0);
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            }
            wsCloseFlag = true;
            totalFlag = true;
            end = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //返回的json结果拆解
    class JsonParse {
        Header header;
        Payload payload;

        @Override
        public String toString() {
            return "JsonParse{" +
                    "header=" + header +
                    ", payload=" + payload +
                    '}';
        }
    }

    class Header {
        int code;
        int status;
        String sid;

        @Override
        public String toString() {
            return "Header{" +
                    "code=" + code +
                    ", status=" + status +
                    ", sid='" + sid + '\'' +
                    '}';
        }
    }

    class Payload {
        Choices choices;

        @Override
        public String toString() {
            return "Payload{" +
                    "choices=" + choices +
                    '}';
        }
    }

    class Choices {
        List<Text> text;

        @Override
        public String toString() {
            return "Choices{" +
                    "text=" + text +
                    '}';
        }
    }

    class Text {
        String role;
        String content;

        @Override
        public String toString() {
            return "Text{" +
                    "role='" + role + '\'' +
                    ", content='" + content + '\'' +
                    '}';
        }
    }

    class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        @Override
        public String toString() {
            return "RoleContent{" +
                    "role='" + role + '\'' +
                    ", content='" + content + '\'' +
                    '}';
        }
    }
}
